import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { getPagination, mapToObj } from 'src/utils';
import { Repository } from 'typeorm';
import { MakeapieEntity } from './entity/makeapie.entity';

@Injectable()
export class MakeapieService {
  constructor(
    @InjectRepository(MakeapieEntity)
    private readonly makeapieRepository: Repository<MakeapieEntity>,
  ) {}

  // 获取 chart 图表
  async findAllEcharts(query): Promise<any> {
    const { page = 1, pageSize = 10 } = query;
    // 自定义查询条件
    const queryMap = new Map();
    queryMap.set('isStared', 0);

    const getList = this.makeapieRepository
      .createQueryBuilder('makeapie')
      .where(mapToObj(queryMap))
      .select([
        'makeapie.id',
        'makeapie.cid',
        'makeapie.authorUid',
        'makeapie.authorUserName',
        'makeapie.title',
        'makeapie.description',
        'makeapie.latestVersion',
        'makeapie.alwaysLatest',
        'makeapie.createTime',
        'makeapie.lastUpdateTime',
        'makeapie.auth',
        'makeapie.uid',
        'makeapie.publishedVersion',
        'makeapie.forkFrom',
        'makeapie.isSpam',
        'makeapie.version',
        'makeapie.parentVersion',
        'makeapie.echartsVersion',
        'makeapie.versionCreateTime',
        'makeapie.code',
        'makeapie.html',
        'makeapie.externalScripts',
        'makeapie.updaterUID',
        'makeapie.theme',
        'makeapie.layout',
        'makeapie.viewCount',
        'makeapie.userName',
        'makeapie.commentCount',
        'makeapie.starCount',
        'makeapie.isStared',
        'makeapie.thumbnailURL',
        'makeapie.isCustomThumbnail',
        'makeapie.builtinTags',
        'makeapie.customTags',
        'makeapie.updaterUserName',
        'makeapie.avatar',
      ])
      .skip((page - 1) * pageSize)
      .take(pageSize)
      .printSql()
      .getManyAndCount();

    const [list, total] = await getList;
    const pagination = getPagination(total, pageSize, page);
    const result = {
      result: list,
      pagination,
    };

    return result;
  }
}
